package cn.lucky.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author lingpeng.jiang
 * @create 2020-12-27-14:47
 */
@Component
public class ConsumerRoundRobinRule implements IConsumerRoundRobinRule {

    private AtomicInteger nextServerCyclicCounter = new AtomicInteger(0);

    /**
     * 获取下一个服务的下标
     * @param serverCount
     * @return
     */
    private final int getAndIncrement(int serverCount){
        int current;
        int next;
        for (;;){
            current = nextServerCyclicCounter.get();
            next = (current + 1) % serverCount;
            if (nextServerCyclicCounter.compareAndSet(current,next)){
                System.out.println("********* next : " + next);
                return next;
            }

        }
    }

    public ServiceInstance getServiceInstance(List<ServiceInstance> serviceInstances) {
        int serverCount = serviceInstances.size();
        int nextServerIndex = this.getAndIncrement(serverCount);
        return serviceInstances.get(nextServerIndex);
    }
}
